import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yurun_smartmerchants/generated/json/base/json_convert_content.dart';
import 'package:yurun_smartmerchants/models/batch_entity.dart';
import 'package:yurun_smartmerchants/models/good_list_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/res/colours.dart';
import 'package:yurun_smartmerchants/utils/DialogUtil.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';
import 'package:yurun_smartmerchants/view/EmptyView.dart';
import 'package:yurun_smartmerchants/view/custom_loadmore_footer.dart';
import 'package:yurun_smartmerchants/view/custom_refresh_header.dart';
import 'package:yurun_smartmerchants/interface/baosuncallback.dart';
import 'package:yurun_smartmerchants/models/baosun_entity.dart';

class InventoryBatchPage extends StatefulWidget{
  final GoodListContent goodContent;

  InventoryBatchPage({this.goodContent});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _InventoryBatchPageState();
  }

}

class _InventoryBatchPageState extends State<InventoryBatchPage> implements BaoSunCallback{
  List<BatchContent> bachList = List();
  int page = 0;
  final int size = 15;
  bool isRefreshOrLoad = false;
  bool empty = false;
  int currentIndex = 0;

  EasyRefreshController _easyRefreshController = EasyRefreshController();

  void statusRefreshLoad(load,last){
    if(page == 0){
      _easyRefreshController.finishRefresh(success: load);
    }
    _easyRefreshController.finishLoad(success: load,noMore: last);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _getInventoryBatch();
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Container(
        color: Colours.app_background,
        child: Column(
          children: <Widget>[
            Container(
              color: Color(0xfffcf7e9),
              margin: EdgeInsets.only(top: AppSize.height(20)),
              height: AppSize.height(66),
              child: Row(
                children: <Widget>[
                  Expanded(
                      flex:1,
                      child: Container(
                        alignment: Alignment.center,
                        child: Text('批次号',style: TextStyle(fontSize: AppSize.sp(22),color: Colours.color_434343),),
                      )),
                  VerticalDivider(
                    thickness: AppSize.width(2),
                    width: AppSize.width(2),
                    color: Colours.color_dcdcdc,
                    indent: AppSize.height(20),
                    endIndent: AppSize.height(20),
                  ),
                  Expanded(
                      flex:1,
                      child: Container(
                        alignment: Alignment.center,
                        child: Text('剩余数量',style: TextStyle(fontSize: AppSize.sp(22),color: Colours.color_434343),),
                      ))
                ],
              ),
            ),
            Expanded(
                child: CupertinoScrollbar(
                    child: EasyRefresh(
                        controller: _easyRefreshController,
                        header: CustomRefreshHeader(),
                        footer: CustomLoadFooter(),
                        emptyWidget: empty ? EmptyView(content: '暂无数据',) : null,
                        onRefresh: () async {
                          isRefreshOrLoad = true;
                          page = 0;
                          _getInventoryBatch();
                        },
                        onLoad: () async {
                          isRefreshOrLoad = true;
                          page ++;
                          _getInventoryBatch();
                        },
                        child: ListView.builder(
                        physics: BouncingScrollPhysics(),
                        itemCount: bachList.length,
                        itemBuilder: (BuildContext context,int index){
                          return listItemView(index);
                        }
                    )
                    )
                )
            )
          ],
        ),
      ),
    );
  }

  Widget listItemView(index){
    return Container(
      color: index % 2 == 0 ? Colours.white : Color(0xfff9f9f9),
      height: AppSize.height(66),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: Text(bachList[index].batchNo,style: TextStyle(fontSize: AppSize.sp(24),color: Colours.color_434343)),
              )
          ),
          Expanded(
              flex: 1,
              child: Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      alignment: Alignment.centerRight,
                      width: AppSize.width(130),
                      child: Text(bachList[index].quantity + bachList[index].unit,style: TextStyle(fontSize: AppSize.sp(24),color: Colours.color_434343)),
                    ),
                    bachList[index].id == null ? damaged(index) : damagedProcess(),
                  ],
                ),
              )
          ),
        ],
      ),
    );
  }

  ///报损
  Widget damaged(index){
    return Container(
      margin: EdgeInsets.only(left: AppSize.width(10)),
      padding: EdgeInsets.only(left: AppSize.width(15),right: AppSize.width(15),bottom: AppSize.height(3)),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(4)),
          border: Border.all(width: 1,color: Color(0xffe87e37))
      ),
      child: GestureDetector(
        onTap: (){
          currentIndex = index;
          DialogUtil.d.showBaoSunDialog(context, '确定',false, this);
        },
        child: Text('报损',style: TextStyle(fontSize: AppSize.sp(22),color: Color(0xffe87e37))),
      ),
    );
  }

  ///报损中
  Widget damagedProcess(){
    return Container(
      margin: EdgeInsets.only(left: AppSize.width(10)),
      child: Text('报损中',style: TextStyle(fontSize: AppSize.sp(22),color: Color(0xff53a949))),
    );
  }

  @override
  void callback({String quantity}) {
    // TODO: implement callback
//    showToast('报损数量:' + quantity);
    _damaged(quantity);
  }

  void _getInventoryBatch(){
    int id = widget.goodContent.id;
    if(!isRefreshOrLoad){
      LoadingUtil.showLoading(context,tip: '加载中...');
    }
    ApiInterface.getInventoryBatch(id,page,size).then((value) {
      BatchEntity batchEntity = JsonConvert.fromJsonAsT<BatchEntity>(value);
      setState(() {
        if(page == 0){
          bachList.clear();
        }
        if(batchEntity.content != null && batchEntity.content.length > 0){
          bachList.addAll(batchEntity.content);
        }
        if(bachList.length == 0){
          empty = true;
        }else{
          empty = false;
        }
      });
      statusRefreshLoad(true, batchEntity.totalPage < 15);
      if (bachList.length > 0) {
        if (isRefreshOrLoad && page == 0) {
          showToast("刷新成功");
        } else if (batchEntity.totalPage < 15 && page > 0) {
          showToast("暂无更多数据");
        }
      }
    }).catchError((error){
      statusRefreshLoad(false, true);
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }

  void _damaged(quantity){
    int id = bachList[currentIndex].id;
    LoadingUtil.showLoading(context);
    ApiInterface.damaged(id, quantity).then((value){
      BaosunEntity baosunEntity = JsonConvert.fromJsonAsT<BaosunEntity>(value);
      bool success = baosunEntity.success;
      if(success){
        showToast('报损提交成功');
      }
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }

}